package com.lgp.main;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.lgp.util.HttpClientUtils;

public class Votes {
	public static void main(String[] args) throws Exception {
//		String s = HttpClientUtils.downloadPage("http://www.stilllistener.com/checkpoint1/test11/");
//		Document doc = Jsoup.connect("http://www.stilllistener.com/checkpoint1/test11/").get();
		
//		System.out.println(s);
//		if(true) return;
		
		List<String> ipList = getIp();  //获取ip
		
		System.out.println("总共获取到"+ipList.size()+"个ip");
		if(ipList.size() <= 0){
			System.out.println("没有获取到ip");
			return;
		}
		
		
		
		int succCount = 0;
		succCount = vote(ipList, succCount); //投票
		
		System.out.println("总共成功了"+succCount+"次");
	}

	/**
	 * 投票
	 * @param ipList
	 * @param succCount
	 * @return
	 */
	private static int vote(List<String> ipList, int succCount) {
		for (int i = 0, count = ipList.size(); i < count; i++) {
			String ipPort = ipList.get(i);
			System.out.println("第" + i + "次，使用的ip=" + ipPort);
			String ip = ipPort.substring(0,ipPort.indexOf(":"));
			int port = Integer.parseInt(ipPort.substring(ipPort.indexOf(":")+1));
			
			//判断ip是否高匿ip
			//参考 http://blog.sina.com.cn/s/blog_6b3676c40100y2e1.html，博客里的检测ip的网址写错了，
			//正确地址：http://www.stilllistener.com/checkpoint1/test11/
			String s = HttpClientUtils.sendGetRequest("http://www.stilllistener.com/checkpoint1/test11/", true, ip, port);
			
			
			String url = "http://www.snowsx.com/love.aspx";
			Map<String, String> paramMap = new HashMap<String,String>();
//			paramMap.put("albumID", "3960");
			paramMap.put("albumID", "4456");
			String resp = HttpClientUtils.sendHttpRequestByProxy(url, paramMap, "POST", "UTF-8", 10000, 10000,ip,port);
			if(resp.contains("Success")){
				succCount++ ;
			}
			System.out.println(resp);
		}
		return succCount;
	}

	/**
	 * 获取ip
	 * @return
	 */
	private static List<String> getIp() {
		//http://www.66ip.cn/pt.html  访问这个网站获取ip的api
		String respIp = HttpClientUtils.sendGetRequest("http://www.66ip.cn/nmtq.php?getnum=30&isp=0&anonymoustype=4&start=&ports=&export=&ipaddress=&area=1&proxytype=0&api=66ip", false, null, null);
		System.out.println(respIp);
		List<String> ipList = new ArrayList<String>();
		//使用正则提取ip
		String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}:\\d{1,5}";
		Pattern p = Pattern.compile(rexp);
		Matcher m = p.matcher(respIp);
		while (m.find()) {
			ipList.add(m.group());
		}
		return ipList;
	}
}
